package com.hands.sample.controller;

import com.hands.commen.entity.wx.*;
import com.hands.commen.utils.GZipHelper;
import com.hands.commen.utils.RandomUtils;

import com.hands.sample.service.InstructionsInfoService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServlet;
import java.util.concurrent.ExecutionException;


/**
 * TODO ：处理调用接口方法控制器
 * author：yanpeixin
 * date  ：2019-07-03
 */

 @Controller
 @RestController
 @RequestMapping("/v1/haier")
public class HaierController extends HttpServlet {

    private static final Logger logger = LoggerFactory.getLogger(HaierController.class);
    @Autowired
    private InstructionsInfoService instructionsInfoService;

    ///设备控制
    @PostMapping(value = "/run")
    public String method(@RequestBody HaierArgs args) throws ExecutionException, InterruptedException {
        logger.info("请求参数{}",args);
        String retrunMsg = null;
        retrunMsg=runToHome(args);
        return retrunMsg;
    }

    @PostMapping(value = "/car")
    public String carmethod(@RequestBody HaierCar args){

        String retrunMsg = null;
        retrunMsg=carcontrol(args);
        return retrunMsg;
    }

    /**
     * 智慧家庭
     * @param args
     * @return
     */
    public String runToHome(HaierArgs args) throws ExecutionException, InterruptedException {
        String returnMsg = null;
        String body = "";
        String msgid="#http"+ RandomUtils.getShortUuid();
        //执行动作标签


        try
        {

            int strAction = args.getCommand().getCommandType();
            MsgEntity msg = new MsgEntity();
            msg.setHeader(new MsgHeader());
            msg.getHeader().setOs(4);
            msg.getHeader().setMsgId(msgid);
            msg.getHeader().setMac(msgid);
            msg.getHeader().setBizCode(args.getCommand().getCommandType());
            ///根据房间号，别名获取主板mac地址
            if (StringUtils.isNotBlank(args.getBaseInfo().getDevMac())) {
                msg.getHeader().setToUserId(args.getBaseInfo().getDevMac());
            }else {
                msg.getHeader().setToUserId(args.getBaseInfo().getRoomNo());
            }
            logger.info("房间号：{}",args.getCommand().getRoomId());
            switch (strAction){
                case 801:
                    body="";
                    break;
                case 815:
                    body ="{\"pageNo\":"+args.getCommand().getPageNo()+",\"pageSize\":"+args.getCommand().getPageSize()+",\"roomId\":"+args.getCommand().getRoomId()+"}";
                    break;
                case 903:
                    body ="{\"pageNo\":"+args.getCommand().getPageNo()+",\"pageSize\":"+args.getCommand().getPageSize()+"}";
                    break;
                case 908:
                    body ="{\"sceneInfo\":{\"sceneId\":\""+args.getCommand().getSceneId()+"\"}}";
                    break;
                case 816:
                    String devtype="";
                    for (int i=0;i<args.getCommand().getDevTypeList().size();i++)
                    {
                        devtype= devtype + "\""+args.getCommand().getDevTypeList().get(i)+"\",";
                    }
                    if (devtype.length()>0) {
                        devtype = devtype.substring(0, devtype.length() - 1);
                    }
                    body ="{\"pageNo\":"+args.getCommand().getPageNo()+",\"pageSize\":"+args.getCommand().getPageSize()+",\"devTypeList\":["+devtype+"]}";
                    break;
                case 812:
                    String actstr="\"devId\":"+args.getCommand().getDevId()+",";
                    if (args.getCommand().getBrightness()>-1){
                        actstr=actstr+"\"brightness\":"+args.getCommand().getBrightness()+",";
                    }
                    if (args.getCommand().getColdWarm()>-1) {
                        actstr = actstr + "\"coldWarm\":" + args.getCommand().getColdWarm() + ",";
                    }
                    if (args.getCommand().getSaturation()>-1) {
                        actstr = actstr + "\"saturation\":" + args.getCommand().getSaturation() + ",";
                    }
                    actstr = actstr.substring(0,actstr.length()-1);
                    body ="{"+actstr+"}";
                    break;
                case 813:
                case 814:
                    body ="{\"devId\":"+args.getCommand().getDevId()+"}";
                    break;

                default:
                    break;
            }
            if (body.length()>0) {
                body = Base64Util.encode(GZipHelper.compress(body, "UTF-8"));
                msg.setBody(body);
            }
            logger.info("传输的数据{}",msg);
            returnMsg = instructionsInfoService.requestHaierSocket(msg); //SocketClient.requestHaierSocket(msg);//用户，开灯状态码，设备ID
            return returnMsg;
        } catch (Exception e)
        {
            //log.writeFile("","出错："+e.toString()+",出错时间："+log.getCurrentYYYYMMDDHHMMSS());
            return "{\"statusCode\": 400,\"message\": \"输入参数解析异常，请检测\",\"result\":\"\"}";
        }


    }

    public String carcontrol(HaierCar args){
        String returnMsg = null;
        String body = "";
        String msgid="#http"+RandomUtils.getShortUuid();
        //执行动作标签


        try
        {
            int strAction = args.getCommand().getCommandType();
            MsgEntity msg = new MsgEntity();
            msg.setHeader(new MsgHeader());
            msg.getHeader().setOs(4);
            msg.getHeader().setMsgId(msgid);
            msg.getHeader().setMac(msgid);
            msg.getHeader().setBizCode(args.getCommand().getCommandType());
            switch (strAction){
                case 5818:
                case 5817:
                    return "{\"statusCode\": 200,\"message\": \"\",\"result\":\"\"}";
                case 5816:
                    String temp="{\"statusCode\":200,\"message\":\"success\",\"result\":{\"carList\":[{\"carNum\":\"浙A12345\",\"serialNumber\":\" OEDER123456\",\"parkingLotCode\":\"\",\"enterModel\":1,\"exitModel\":1,\"startTimeStr\":\"2017-05-10 10:00:00\",\"endTimeStr\":\"2017-05-10 20:00:00\"}]}}";
                    return temp;
                default:
                    break;
            }
            if (body.length()>0){
                body= Base64Util.encode(GZipHelper.compress(body,"UTF-8"));
            }
            msg.setBody(body);
            returnMsg =instructionsInfoService.requestHaierSocket(msg); //SocketClient.requestHaierSocket(msg);//用户，开灯状态码，设备ID
            return returnMsg;
        } catch (Exception e)
        {
            //log.writeFile("","出错："+e.toString()+",出错时间："+log.getCurrentYYYYMMDDHHMMSS());
            return "{\"statusCode\": 400,\"message\": \"输入参数解析异常，请检测\",\"result\":\"\"}";
        }


    }

}
